// index.tsx
import React, {useEffect, useState} from 'react';
import Taro from '@tarojs/taro';
import {Image, Text, View} from '@tarojs/components';
import {GetFoodCates} from '../../../api/bus/food';
import {GetCurHotel} from '../../../api/config';
import './index.scss';
import {modelToast, transferDay} from '../../../utils';
import Popup from "../../../components/view/Popup";
import HeadTitle from "../../../components/view/HeadTitle";
import {FoodCateItem, FoodOrderItem, IFoodCateItem} from "../com/FoodItem";
import '../../../reset.scss'
import {setStoreSaveList} from "../../../utils/storage";

export const FoodPre: React.FC = (): JSX.Element => {
  const [list, setList] = useState([]);
  const [saveList, setSaveList] = useState([]);
  const [hotelInfo, setHotelInfo] = useState<IHotelInfo>({
    BreakfastEndTime: '',
    BreakfastStartTime: '',
    Date: '',
    HotelAdd: '',
    HotelName: '',
  });
  const [popupShow, setPopupShow] = useState(false);

  useEffect(() => {
    onSetHotelInfo();
    onGetFoodCates();
  }, []);

  const onSetHotelInfo = () => {
    GetCurHotel().then((res) => {
      setHotelInfo(res);
    });
  };

  const onGetFoodCates = () => {
    GetFoodCates().then((res) => {
      setList(res.map((item) => ({...item, num: 1})));
    });
  };

  const add = 'add';
  const del = 'del';
  const edit = 'edit';
  const reset = 'reset';

  type TSetSaveList =
    | {
    type: typeof add;
    item: IFoodCateItem;
  }
    | {
    type: typeof del;
    Id: string;
  }
    | {
    // 需要所有属性都可以替换
    type: typeof edit;
    Id: string;
    item: IFoodCateItem;
  }
    | {
    type: typeof reset;
    list: Array<IFoodCateItem> | [];
  };

  const onSetSaveList = (action: TSetSaveList) => {
    setSaveList((stateList) => {
      let newStateList;
      // 根据action进行相应的处理
      switch (action.type) {
        case add:
          newStateList = [...stateList, action.item];
          break;
        case del:
          newStateList = stateList.filter((item) => item.Id !== action.Id);
          break;
        case edit:
          newStateList = stateList.map((item) => (item.Id === action.Id ? {...item, ...action.item} : item));
          break;
        case reset:
          newStateList = action.list;
          break;
        default:
          throw new Error('你没有传action.type属性');
      }
      return newStateList;
    });
  };

  const onPopup = (item: IFoodCateItem) => {
    const shouldOpen = () => {
      setPopupShow(true);
      onSetSaveList({type: add, item});
    };
    const filItem: IFoodCateItem = saveList.filter((saveItem) => saveItem.Id === item.Id)[0];
    if (filItem) {
      setPopupShow(true);
      return modelToast({title: '已经点过它了~'})
    } else {
      shouldOpen();
    }
  };

  return (
    <View className='FoodPre'>
      <BgTop info={hotelInfo}></BgTop>
      <Popup
        title='我的购物车'
        isOpened={popupShow}
        onClose={() => setPopupShow(false)}
        customStyle={{height: '360px', paddingBottom: '80px'}}
        onOverlay={() => {
          setPopupShow(false);
        }}
        customHeader={
          <PopupHead total={saveList.length} reset={() => onSetSaveList({type: reset, list: []})}></PopupHead>
        }
      >
        <View>
          {saveList.map((saveItem) => (
            <FoodOrderItem
              key={saveItem.Id}
              delItem={(Id) => onSetSaveList({type: del, Id})}
              editItem={(params) => onSetSaveList({type: edit, Id: params.Id, item: {...saveItem, ...params}})}
              item={saveItem}
            ></FoodOrderItem>
          ))}
          <PopupEnd HotelName={hotelInfo.HotelName} list={saveList}></PopupEnd>
        </View>
      </Popup>
      <View className='Wrapper'>
        <HeadTitle
          title={hotelInfo.HotelName}
          bgColor='transparent'
          subTitle={hotelInfo.Date?.slice(0, 10) + ' ' + transferDay(new Date().getDay())}
        ></HeadTitle>
        <View className='List'>
          {list.map((item) => (
            <View key={item.Id} onClick={() => onPopup(item)}>
              <FoodCateItem item={item}></FoodCateItem>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
};

export const BgTop = React.memo(function (props: { info: IHotelInfo }): JSX.Element {
  const {info} = props;
  return (
    <View className='BgTop'>
      <Image lazyLoad mode='aspectFit' className='bgImg' src={require('@/static/images/food/f_pre/topBg.png')}></Image>
      <View className='content'>
        <View className='title'>{info.HotelName}</View>
        <View className='subTitle'>{info.HotelAdd}</View>
        <View className='food'>
          <View className='time'>
            <Text className='text'>早餐时间: {info.BreakfastStartTime} - {info.BreakfastEndTime}</Text>
          </View>
        </View>
      </View>
    </View>
  );
});


const PopupHead: React.FC<IPopupHead> = ({total, reset}) => {
  return (
    <View className='popupHeader align-center justify-between'>
      <View className='left'>我的购物车（{total}）</View>
      <View className='right align-center' onClick={() => reset()}>
        <Image lazyLoad className='img' src={require('@/static/images/food/f_pre/delete.png')}></Image>
        <Text className='text'>清空购物车</Text>
      </View>
    </View>
  );
};

const PopupEnd: React.FC<IPopupEnd> = ({list, HotelName}) => {
  const saveTotal = list.reduce((accumulator, currentValue) => accumulator + currentValue.num, 0);
  const onEnd = () => {
    // 下单操作
    setStoreSaveList(list);
    return Taro.navigateTo({url: 'subPages/food/f_submit/index?HotelName=' + HotelName});
  };
  return (
    <View className='popupEnd'>
      <View className='content justify-between align-center'>
        <View className='left align-center'>
          <Image className='icon' lazyLoad src={require('@/static/images/food/f_pre/sure.png')}></Image>
          <View className='radius flex-center'>{saveTotal}</View>
        </View>
        <View className='right' onClick={onEnd}>
          选好了
        </View>
      </View>
    </View>
  );
};

export interface IPopupHead {
  total: number;
  reset: Function;
}

export interface IPopupEnd {
  list: Array<IFoodCateItem>;
  HotelName: string,
}


export interface IHotelInfo {
  HotelName: string;
  HotelAdd: string;
  BreakfastStartTime: string;
  BreakfastEndTime: string;
  Date: string;
}

export default FoodPre;
